<?php
use Phalcon\Cli\Task;
use Common\Common;

class OrdersyncTask extends Task
{
    //上个月
    public function last_month_last_day($bool)
    {

        $last = strtotime("-1 month", time());
        if ($bool) {
            return date("Y-m-t 23:59:59", $last);//上个月最后一天
        }
        return date("Y-m-01 00:00:00", $last);//上个月第一天
    }

    /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~start taobao~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
    public function taobao_order_deal($data)
    {
        //拉取订单的集合
        //订单数组
        $order = [];
        //都好分割的数据
        $in_ids = '';
        //数据库返回的存在数据
        /*
			0	默认
			1	待支付
			2	已支付
			3	已退款
			4	已完成
			5	已失效
			6	已结算
			11	已取消
			3：订单结算，
			12：订单付款，
			13：订单失效，
			14：订单成功
		 */
        $status = [
            12 => 2,
            13 => 5,
            14 => 4,
            3  => 6,
        ];
        //拿到所有用

        $user_relation = array_unique(array_column($data, 'relation_id'));
        $user          = new \Common\Models\User();
        $user_arr      = [];
        if ($user_relation != []) {
            $user_arr = $user->get_user_id_by_tb_rid($user_relation);
        }
        $order_model = new \Common\Models\Order();
        foreach ($data as $k => $v) {
            $order_id     = $v['trade_id'];
            $order_status = $status[$v['tk_status']];
            //			$v['total_commission_fee']=rand(99,1000);
            if (!isset($v['relation_id'])) {
                $v['relation_id'] = '0';
            }
            $site = 'haodanku';
            if ($v['order_type'] == '饿了么') {
                $site = 'elm';
            }
            if ($v['order_type'] == '口碑') {
                $site = 'koubei';
            }
            $old_commition = doubleval($v['pub_share_fee']) > 0 ? $v['pub_share_fee'] : $v['pub_share_pre_fee'];    //原来的佣金
            $commition = Common::commission($user_arr[$v['relation_id']],$old_commition);                           //计算过后的佣金

            $order_one = [
                'user_id'            => isset($user_arr[$v['relation_id']]) ? $user_arr[$v['relation_id']] : $v['relation_id'],
                'order_id'           => $order_id,
                'order_status'       => $order_status,
                'goods_name'         => $v['item_title'],
                'goods_id'           => isset($v['item_id']) ? $v['item_id'] : '',
                'goods_pic'          => $v['item_img'],
                'site'               => $site,
                'rid'                => $v['relation_id'],
                'shop_name'          => $v['seller_nick'],
                'price'              => isset($v['item_price']) ? $v['item_price'] : $v['alipay_total_price'],
                'pay_money'          => isset($v['alipay_total_price']) ? $v['alipay_total_price'] : 0,
                'commition'          => $commition['commisson'],
                'income_rate'        => $v['total_commission_rate'] ? $v['total_commission_rate'] : $v['income_rate'],
                'order_create_time'  => $v['tk_create_time'],
                'order_paid_time'    => isset($v['tk_paid_time']) ? $v['tk_paid_time'] : null,
                'order_earning_time' => isset($v['tk_earning_time']) ? $v['tk_earning_time'] : null,
                'settle_time'        => isset($v['tk_earning_time']) ? $v['tk_earning_time'] : null,
                'rate_service'         =>$commition['rate_money'],
            ];
            if (!isset($order[$order_id])) {

                $order[$order_id]         = $order_one;
                $order_ids_arr[$order_id] = $order_status;

                if ($in_ids == '') {
                    $in_ids = "'$order_id'";
                } else {
                    $in_ids .= ",'$order_id'";
                }
            }
        }

        //淘宝/饿了么
        $db_arr  = $order_model->get_status_by_tb($in_ids, "'elm','haodanku','koubei'");
        $uporder = [];
        if ($db_arr) {
            foreach ($db_arr as $k => $v) {
                $key = $order[$k]['order_status'] . '-' . $order[$k]['user_id'];
                if ($key != $v) {
                    $uid                  = explode('-', $v);
                    $order[$k]['user_id'] = $uid[1];
                    $uporder[$key]        = $order[$k];
                }
                unset($order[$k]);
            }
        }
        //创建订单
        if ($order != []) {
            $order_model->create_update_order($order,1);
        }
        //更新订单
        if ($uporder != []) {
            $order_model->create_update_order($uporder,0);
        }
    }

    /**
     * 淘宝上上月订单 更新订单
     */
    public function taobaoLastLastMonthAction()
    {
        $now     = time();
        $control = new \Common\Models\SyncControl();
        $res     = $control->findFirstBySite('tb_last_month');
        $start   = date('Y-m-d H:i:s', mktime(0, 0, 0, date('m') - 2, 1, date('Y')));
        $end     = date('Y-m-d H:i:s', mktime(23, 59, 59, date('m') - 1, 1 - 1, date('Y')));
        if ($res->end_time > $end) {
            $res->end_time = $start;
        }
        $and           = 2 ;//小时
        $start_time    = $res->end_time;
        $res->end_time = date("Y-m-d H:i:s", strtotime($res->end_time) + $and * 60 * 60);
        $res->save();
        $end_time = $res->end_time;
        $count    = 0;
        //批量处理订单

        $data       = $this->taobao->get_order($start_time, $end_time);
        $other_data = $this->taobao->get_order($start_time, $end_time, null, null, 1);
        if ($other_data != []) {
            $temp_data = [];

            if (!empty($data)) {
                foreach ($data as $val) {
                    $temp_data[$val['trade_id']] = $val;
                }
            }
            foreach ($other_data as $value) {
                if (!isset($temp_data[$value['trade_id']])) {
                    $data[] = $value;
                }
            }
        }
        if ($data != []) {
            $count = count($data);
            $this->taobao_order_deal($data);
        }
        $now = time() - $now;
        die($start_time . '-' . $end_time . '用时:' . $now . '秒,获取' . $count . '条订单');
    }

    /**
     * 淘宝上月订单 更新订单
     */
    public function taobaoLastMonthAction()
    {
        $now      = time();
        $control  = new \Common\Models\SyncControl();
        $res      = $control->findFirstBySite('tb_month');
        $last_day = Common::timeChange(9);

        if ($res->end_time > $last_day['end_at']) {
            $res->end_time = $last_day['start_at'];
        }
        $and           = 2;//小时
        $start_time    = $res->end_time;
        $res->end_time = date("Y-m-d H:i:s", strtotime($res->end_time) + $and * 60 * 60);
        $res->save();
        $end_time = $res->end_time;
        $count    = 0;
        //批量处理订单

        $data       = $this->taobao->get_order($start_time, $end_time);
        $other_data = $this->taobao->get_order($start_time, $end_time, null, null, 1);
        if ($other_data != []) {
            $temp_data = [];

            if (!empty($data)) {
                foreach ($data as $val) {
                    $temp_data[$val['trade_id']] = $val;
                }
            }

            foreach ($other_data as $value) {
                if (!isset($temp_data[$value['trade_id']])) {
                    $data[] = $value;
                }
            }
        }
        if ($data != []) {
            $count = count($data);
            $this->taobao_order_deal($data);
        }
        $now = time() - $now;
        die($start_time . '-' . $end_time . '用时:' . $now . '秒,获取' . $count . '条订单');
    }

    /**
     * 淘宝本月的 更新订单
     */
    public function taobaoThisMonthAction()
    {
        $now     = time();
        $control = new \Common\Models\SyncControl();
        $res     = $control->findFirstBySite('tb_day');
        if ($res->end_time > date('Y-m-d H:i:s')) {
            $res->end_time = date('Y-m-01 00:00:00');
        }
        $and           = 2;//小时
        $start_time    = $res->end_time;
        $res->end_time = date("Y-m-d H:i:s", strtotime($res->end_time) + $and * 60 * 60);
        $res->save();

        $end_time = $res->end_time;
        $count    = 0;

        //批量处理订单
        $data       = $this->taobao->get_order($start_time, $end_time);
        $other_data = $this->taobao->get_order($start_time, $end_time, null, null, 1);
        if ($other_data != []) {
            $temp_data = [];

            if (!empty($data)) {
                foreach ($data as $val) {
                    $temp_data[$val['trade_id']] = $val;
                }
            }

            foreach ($other_data as $value) {
                if (!isset($temp_data[$value['trade_id']])) {
                    $data[] = $value;
                }
            }
        }
        if ($data != []) {
            $count = count($data);
            $this->taobao_order_deal($data);
        }
        $now = time() - $now;
        die($start_time . '-' . $end_time . '用时:' . $now . '秒,获取' . $count . '条订单');
    }

    /**
     * 淘宝每分钟 新订单
     */
    public function taobaoMinAction()
    {
        $now        = time();
        $min        = 18;
        $start      = date("Y-m-d H:i:s", time() - $min * 60);
        $end        = date("Y-m-d H:i:s");
        $data       = $this->taobao->get_order($start, $end, null, null, 0);
        $other_data = $this->taobao->get_order($start, $end, null, null, 1);
        if ($other_data != []) {
            $temp_data = [];

            if (!empty($data)) {
                foreach ($data as $val) {
                    $temp_data[$val['trade_id']] = $val;
                }
            }

            foreach ($other_data as $value) {
                if (!isset($temp_data[$value['trade_id']])) {
                    $data[] = $value;
                }
            }
        }
        if ($data != []) {
            $this->taobao_order_deal($data);
        }
        $now = time() - $now;
        die($start . '-' . date("Y-m-d H:i:s") . '用时:' . $now . '秒,获取' . count($data) . '条订单');
    }

    /**
     * 淘宝今日订单 更新订单
     */
    public function taobaoThisTodayAction()
    {
        $now       = time();
        $redis_key = "taobao_this_today";
        $cache     = new \Common\BaseModel();
        $start     = $cache->get_cache($redis_key);
        if (!$start || $start > $now) {
            $start = strtotime(date('Ymd'));
        }
        $min   = 20;
        $start = date("Y-m-d H:i:s", $start);
        $end   = date("Y-m-d H:i:s", strtotime($start) + $min * 60);
        $cache->set_cache($redis_key, strtotime($end));

        $data = $this->taobao->get_order($start, $end, null, null, 0);

        $other_data = $this->taobao->get_order($start, $end, null, null, 1);

        if ($other_data != []) {
            $temp_data = [];

            if (!empty($data)) {
                foreach ($data as $val) {
                    $temp_data[$val['trade_id']] = $val;
                }
            }

            foreach ($other_data as $value) {
                if (!isset($temp_data[$value['trade_id']])) {
                    $data[] = $value;
                }
            }
        }
        if ($data != []) {
            $this->taobao_order_deal($data);
        }
        $now = time() - $now;
        die($start . '-' . $end . '用时:' . $now . '秒,获取' . count($data) . '条订单');
    }

    /**
     * 淘宝维权订单
     */
    public function taobaoLastMonthWeiquanAction()
    {
        $now      = time();
        $control  = new  \Common\Models\SyncControl();
        $res      = $control->find_by_site('tb_month_weiquan');
        $last_day = date('Y-m-d H:i:s');
        if ($res->end_time > $last_day) {
            $res->end_time = $this->last_month_last_day(0);
            $res->save();
        }
        $start_time = $res->end_time;
        $and        = 24;

        $res->end_time = date("Y-m-d H:i:s", strtotime($start_time) + $and * 60 * 60);
        $res->save();
        $count = 0;
        //批量处理订单
        $data = $this->taobao->get_order_last($start_time);
        if ($data['data']['results'] != []) {
            $count = count($data['data']['results']['result']);
            $this->weiquan_deal($data['data']['results']['result']);
        }
        $now = time() - $now;
        die($start_time . '用时:' . $now . '秒,获取' . $count . '条订单');
    }

    public function weiquan_deal($data)
    {
        foreach ($data as $val) {
            $orderDb = new \Common\Models\Order();
            $where   = "order_id = '{$val['tb_trade_id']}' or order_id = '{$val['tb_trade_parent_id']}'";
            $info    = $orderDb->findFirst($where);
            if ($info) {
                if ($val['refund_status'] == 3) {
                    $info->order_status = 6;
                    $info->remark       = '维权失败!';
                } else {
                    $info->remark       = '维权中订单!';
                    $info->order_status = 5;
                }
                $f_order_commissions  = new \Common\Models\OrderCommissions();
                $wheres['conditions'] = "order_id = '{$info->order_id}'";
                $commission           = $f_order_commissions->find($wheres);
                if (!empty($commission->toarray())) {
                    foreach ($commission as $vals) {
                        if ($val['refund_status'] == 3) {
                            $vals->order_status = 6;
                        } else {
                            $vals->order_status = 5;
                        }
                        $vals->save();
                    }
                }
                $info->save();
            }
        }
    }

    /**
     * 上个月淘宝处罚订单
     */
    public function taobaoLastMonthChufaAction()
    {
        $now      = time();
        $control  = new  \Common\Models\SyncControl();
        $res      = $control->find_by_site('tb_chufa');
        $last_day = date('Y-m-d H:i:s');
        if (strtotime($res->end_time) > strtotime($last_day)) {
            $res->end_time = date('Y-m-d 00:00:00', time() - 80 * 86400);
            $res->save();
        }
        $start_time = $res->end_time;
        $and        = 24;

        $res->end_time = date("Y-m-d H:i:s", strtotime($start_time) + $and * 60 * 60);
        $res->save();
        //批量处理订单
        $count = $this->taobao->get_order_chufa($start_time);


        $now = time() - $now;

        die($start_time . '用时:' . $now . '秒,获取' . $count . '条订单');
    }
    /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~end taobao~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

    /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ start jd~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

    public function jd_order_deal($data)
    {
        //拉取订单的集合
        //订单数组
        $order = [];
        //都好分割的数据
        $in_ids = '';
        //数据库返回的存在数据
        /*
			0	默认
			1	待支付
			2	已支付
			3	已退款
			4	已完成
			5	已失效
			6	已结算
			11	已取消


（-1：未知
2.无效-拆单
3.无效-取消
4.无效-京东帮帮主订单
5.无效-账号异常
6.无效-赠品类目不返佣
7.无效-校园订单
8.无效-企业订单
9.无效-团购订单
10.无效-开增值税专用发票订单
11.无效-乡村推广员下单
12.无效-自己推广自己下单
13.无效-违规订单
14.无效-来源与备案网址不符
15.待付款
16.已付款
17.已完成
18.已结算（5.9号不再支持结算状态回写展示））注：自2018/7/13起，自己推广自己下单已经允许返佣，故12无效码仅针对历史数据有效



		 */
        $status = [
            15 => "1",
            16 => "2",
            17 => "4",
            18 => "6",
        ];
        //拿到所有用
        /*
		$user_relation='';
		foreach($data as $k =>$v){
			$user_id=$v['skuList'][0]['subUnionId'];
			if($user_relation == ''){
			$user_relation=$user_id;
			}else{
				if(!strstr($user_relation,$user_id)){
				$user_relation .=','.$user_id;
				}
			}
		}
		$user= new User();
		$user_arr=$user->get_user_id_by_tb_rid($user_relation);
 */
        $order_model = new \Common\Models\Order();
        foreach ($data as $k => $v) {
            foreach ($v['skuList'] as $k1 => $v1) {
                $pid = '';
                if ($v['parentId'] != 0) {
                    $pid = $v['parentId'] . '_';
                }
                if (count($v['skuList']) == 1) {
                    $order_id = $v['orderId'];
                } else {
                    $order_id = $pid . $v['orderId'] . "_" . ($k1 + 1) . "_" . $v1['skuId'];
                }
                if ($v1['price'] == 0) {
                    //	continue;
                }

                $order_status = $v['validCode'] <= 14 ? 5 : $status[$v['validCode']];
                //	$v1['estimateFee']=rand(99,1000);
                if (strpos($v1['subUnionId'], 'jzjs') === false) {
                    continue;
                }
                $userId                   = explode('_', $v1['subUnionId']);
                $order_one                = [
                    'user_id'            => $userId[1],
                    'order_id'           => $order_id,
                    'order_status'       => $order_status,
                    'goods_name'         => $v1['skuName'],
                    'goods_id'           => $v1['skuId'],
                    'goods_pic'          => '',
                    'site'               => 'jd',
                    'price'              => $v1['price'],
                    'pay_money'          => $v1['actualCosPrice'] > 0 ? $v1['actualCosPrice'] : $v1['estimateCosPrice'],
                    'commition'          => $v1['actualFee'] > 0 ? $v1['actualFee'] : $v1['estimateFee'],
                    'income_rate'        => $v1['commissionRate'],
                    'order_create_time'  => date('Y-m-d H:i:s', $v['orderTime'] / 1000),
                    'order_paid_time'    => $v['payMonth'] != 0 ? substr($v['payMonth'], 0, 4) . '-' . substr($v['payMonth'], 4, 2) . '-' . substr($v['payMonth'], -2) . ' 00:00:00' : null,
                    'order_earning_time' => $v['payMonth'] != 0 ? substr($v['payMonth'], 0, 4) . '-' . substr($v['payMonth'], 4, 2) . '-' . substr($v['payMonth'], -2) . ' 00:00:00' : null,
                    'settle_time'        => $v['payMonth'] != 0 ? substr($v['payMonth'], 0, 4) . '-' . substr($v['payMonth'], 4, 2) . '-' . substr($v['payMonth'], -2) . ' 00:00:00' : null,

                ];
                $order[$order_id]         = $order_one;
                $order_ids_arr[$order_id] = $order_status;

                if ($in_ids == '') {
                    $in_ids = "'$order_id'";
                } else {
                    $in_ids .= ",'$order_id'";

                }
            }
        }

        //订单去重
        $db_arr = $order_model->get_status_by_ids($in_ids, 'jd');

        $uporder = [];
        if ($db_arr) {
            foreach ($db_arr as $k => $v) {
                if ($order[$k]['order_status'] != $v) {
                    $uporder[$k] = $order[$k];
                }
                unset($order[$k]);
            }
        }

        //创建订单
        if ($order != []) {
            foreach ($order as $k => $v) {
                $goods_detail           = $this->jd->goods_detail($v['goods_id']);
                $order[$k]['goods_pic'] = $goods_detail['PicLogo'];
            }

            $order_model->create_update_order($order, 1);
        }
        //更新订单
        if ($uporder != []) {
            foreach ($uporder as $k => $v) {
                $goods_detail             = $this->jd->goods_detail($v['goods_id']);
                $uporder[$k]['goods_pic'] = $goods_detail['PicLogo'];
            }
            $order_model->create_update_order($uporder, 0);
        }

    }


    /**
     * 京东上上月
     */
    public function jdLastLastMonthAction()
    {
        $now     = time();
        $control = new \Common\Models\SyncControl();
        $res     = $control->findFirstBySite('jd_last_month');
        $start   = date('Y-m-d H:i:s', mktime(0, 0, 0, date('m') - 2, 1, date('Y')));
        $end     = date('Y-m-d H:i:s', mktime(23, 59, 59, date('m') - 1, 1 - 1, date('Y')));
        if ($res->end_time > $end) {
            $res->end_time = $start;
        }
//        $and           = 0.2;//小时
        $time_type  = 'hour';
        $start_time = $res->end_time;
        if ($time_type == 'day') {
            $res->end_time = date("Y-m-d H:i:s", strtotime($start_time) + 24 * 3600);
        }
        if ($time_type == 'hour') {
            $res->end_time = date("Y-m-d H:i:s", strtotime($start_time) + 3600);
        }
        $res->save();
        $count = 0;
        //批量处理订单
        $data = $this->jd->get_order($start_time, 'hour', 'add_order_time');
        if ($data != []) {
            $count = count($data);
            $this->jd_order_deal($data);
        }

        $now = time() - $now;
        die($start_time . '-' . $res->end_time . '用时:' . $now . '秒,获取' . $count . '条订单');
    }

    /**
     * 京东上月
     */
    public function jdLastMonthAction()
    {
        $now      = time();
        $control  = new \Common\Models\SyncControl();
        $res      = $control->findFirstBySite('jd_month');
        $last_day = Common::timeChange(9);

        if ($res->end_time > $last_day['end_at']) {
            $res->end_time = $last_day['start_at'];
        }
//        $and           = 0.32;//小时
        $time_type  = 'hour';
        $start_time = $res->end_time;
        if ($time_type == 'day') {
            $res->end_time = date("Y-m-d H:i:s", strtotime($start_time) + 24 * 3600);
        }
        if ($time_type == 'hour') {
            $res->end_time = date("Y-m-d H:i:s", strtotime($start_time) + 3600);
        }
        $res->save();
        $count = 0;
        //批量处理订单
        $data = $this->jd->get_order($start_time, 'hour', 'add_order_time');
        if ($data != []) {
            $count = count($data);
            $this->jd_order_deal($data);
        }

        $now = time() - $now;
        die($start_time . '-' . $res->end_time . '用时:' . $now . '秒,获取' . $count . '条订单');
    }

    /**
     * 京东本月 更新订单
     */
    public function jdThisMonthAction()
    {
        $now     = time();
        $control = new \Common\Models\SyncControl();
        $res     = $control->findFirstBySite('jd_day');
        if ($res->end_time > date('Y-m-d H:i:s')) {
            $res->end_time = date('Y-m-01 00:00:00');
        }
//        $and           = 0.2;//小时
        $start_time    = $res->end_time;
        $res->end_time = date("Y-m-d H:i:s", strtotime($start_time) + 3600);

        $res->save();

        $end_time = $res->end_time;
        $count    = 0;
        //批量处理订单
        $data = $this->jd->get_order($end_time, 'hour', 'add_order_time');
        if ($data != []) {
            $count = count($data);
            $this->jd_order_deal($data);
        }

        $now = time() - $now;
        die($start_time . '-' . $end_time . '用时:' . $now . '秒,获取' . $count . '条订单');
    }


    //jd每分钟
    public function jdMinAction()
    {
        $now   = time();
        $start = date("Y-m-d H:i:00", time() - 60);
        $data  = $this->jd->get_order($start, 'min', 'update_order_time');
        if ($data != []) {
            $this->jd_order_deal($data);
        }
        $now = time() - $now;
        die($start . '-' . date("Y-m-d H:i:59") . '用时:' . $now . '秒,获取' . count($data) . '条订单');
    }
    /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~end jd~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

    /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ start pdd~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
    /*
     拼多多订单处理
     */
    public function pdd_order_deal($data)
    {
        //拉取订单的集合
        //订单数组
        $order = [];
        //都好分割的数据
        $in_ids = '';
        //数据库返回的存在数据
        /*
			0	默认
			1	待支付
			2	已支付
			3	已退款
			4	已完成
			5	已失效
			6	已结算
			11	已取消


			订单状态：
			-1 未支付
			0-已支付
1-已成团
2-确认收货
3-审核成功
4-审核失败（不可提现）
5-已经结算
8-非多多进宝商品（无佣金订单）


		 */
        $status = [
            '-1' => 1,
            '0'  => 2,
            '1'  => 2,
            '2'  => 4,
            '3'  => 4,
            '4'  => 11,
            '5'  => 6,
            '8'  => 4
        ];
        //拿到所有用
        $user_relation = array_unique(array_column($data, 'p_id'));
        $user          = new \Common\Models\User();
        $user_arr      = $user->get_user_id_by_pdd_pid($user_relation);
        $order_model   = new \Common\Models\Order();
        foreach ($data as $k => $v) {
            if (!$user_arr[$v['p_id']]) {
                continue;
            }
            $order_id     = $v['order_sn'];
            $order_status = $status[$v['order_status']];
            //	$v['total_commission_fee']=rand(99,1000);
            $order_one                = [
                'user_id'            => isset($user_arr[$v['p_id']]) ? $user_arr[$v['p_id']] : $v['p_id'],
                'order_id'           => $order_id,
                'order_status'       => $order_status,
                'goods_name'         => $v['goods_name'],
                'goods_id'           => $v['goods_id'],
                'goods_pic'          => $v['goods_thumbnail_url'],
                'site'               => 'pdd',
                'price'              => $v['goods_price'] / 100,
                'pay_money'          => isset($v['order_amount']) ? $v['order_amount'] / 100 : 0,
                'commition'          => $v['promotion_amount'] / 100,
                'income_rate'        => $v['promotion_rate'] * 10,
                'order_create_time'  => date("Y-m-d H:i:s", $v['order_create_time']),
                'order_paid_time'    => isset($v['order_pay_time']) ? date("Y-m-d H:i:s", $v['order_pay_time']) : null,
                'settle_time'        => isset($v['order_settle_time']) ? date("Y-m-d H:i:s", $v['order_settle_time'] / 1000) : null,
                'order_earning_time' => null,

            ];
            $order[$order_id]         = $order_one;
            $order_ids_arr[$order_id] = $order_status;

            if ($in_ids == '') {
                $in_ids = "'$order_id'";
            } else {
                $in_ids .= ",'$order_id'";

            }

        }

        //订单去重
        if ($in_ids) {
            $db_arr  = $order_model->get_status_by_ids($in_ids, 'pdd');
            $uporder = [];
            if ($db_arr) {
                foreach ($db_arr as $k => $v) {
                    if ($order[$k]['order_status'] != $v) {
                        if ($order[$k]['order_status'] == 6) {
                            $order[$k]['order_earning_time'] = date("Y-m-d H:i:s");
                        }
                        $uporder[$k] = $order[$k];
                    }
                    unset($order[$k]);
                }
            }
            //创建订单
            if ($order != []) {
                $order_model->create_update_order($order, 1);
            }
            //更新订单
            if ($uporder != []) {
                $order_model->create_update_order($uporder, 0);
            }
        }
    }

    /**
     * 拼多多上上月
     */
    public function pddLastLastMonthAction()
    {
        $now     = time();
        $control = new \Common\Models\SyncControl();
        $res     = $control->findFirstBySite('pdd_month');
        $start   = date('Y-m-d H:i:s', mktime(0, 0, 0, date('m') - 2, 1, date('Y')));
        $end     = date('Y-m-d H:i:s', mktime(23, 59, 59, date('m') - 1, 1 - 1, date('Y')));
        if ($res->end_time > $end) {
            $res->end_time = $start;
        }
        $and           = 20;//小时
        $start_time    = $res->end_time;
        $res->end_time = date("Y-m-d H:i:s", strtotime($res->end_time) + $and * 60);
        $res->save();
        $end_time = $res->end_time;
        $count    = 0;
        //批量处理订单
        $data = $this->pdd->get_order($start_time, $end_time);
        if ($data != []) {
            $count = count($data);
            $this->pdd_order_deal($data);
        }
        $now = time() - $now;
        die($start_time . '-' . $end_time . '用时:' . $now . '秒,获取' . $count . '条订单');
    }

    /**
     * 拼多多上月
     */
    public function pddLastMonthAction()
    {
        $now      = time();
        $control  = new \Common\Models\SyncControl();
        $res      = $control->findFirstBySite('pdd_month');
        $last_day = Common::timeChange(9);
        if ($res->end_time > $last_day['end_at']) {
            $res->end_time = $last_day['start_at'];
        }
        $and           = 20;//分钟
        $start_time    = $res->end_time;
        $res->end_time = date("Y-m-d H:i:s", strtotime($res->end_time) + $and * 60);
        $res->save();
        $end_time = $res->end_time;
        $count    = 0;
        //批量处理订单
        $data = $this->pdd->get_order($start_time, $end_time);
        if ($data != []) {
            $count = count($data);
            $this->pdd_order_deal($data);
        }
        $now = time() - $now;
        die($start_time . '-' . $end_time . '用时:' . $now . '秒,获取' . $count . '条订单');
    }

    /**
     * 拼多多本月
     */
    public function pddThisMonthAction()
    {
        $now     = time();
        $control = new \Common\Models\SyncControl();
        $res     = $control->findFirstBySite('pdd_day');
        if ($res->end_time > date('Y-m-d H:i:s')) {
            $res->end_time = date('Y-m-01 00:00:00');
        }
        $and           = 20;//分钟
        $start_time    = $res->end_time;
        $res->end_time = date("Y-m-d H:i:s", strtotime($res->end_time) + $and * 60);
        $res->save();
        $end_time = $res->end_time;
        $count    = 0;
        //批量处理订单
        $data       = $this->pdd->get_order($start_time, $end_time);
        if ($data != []) {
            $count = count($data);
            $this->pdd_order_deal($data);
        }
        $now = time() - $now;
        die($start_time . '-' . $end_time . '用时:' . $now . '秒,获取' . $count . '条订单');
    }

    /*
	 拼多多每分钟
	 */
    public function pddMinAction()
    {
        $now   = time();
        $min   = 5;
        $start = date("Y-m-d H:i:s", time() - $min * 60);
        $end   = date("Y-m-d H:i:s");
        $data  = $this->pdd->get_up_order(strtotime($start), strtotime($end));
        if ($data != []) {
            $this->pdd_order_deal($data);
        }
        $now = time() - $now;
        die($start . '-' . $end . '用时:' . $now . '秒,获取' . count($data) . '条订单');
    }
    /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~end pdd~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

    /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ start vph~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

    public function vph_order_deal($data)
    {
        //拉取订单的集合
        //订单数组
        $order = [];
        //都好分割的数据
        $in_ids = '';
        //数据库返回的存在数据
        /*
            0	默认
            1	待支付
            2	已支付
            3	已退款
            4	已完成
            5	已失效
            6	已结算
            11	已取消
（-1：未知
2.无效-拆单
3.无效-取消
4.无效-京东帮帮主订单
5.无效-账号异常
6.无效-赠品类目不返佣
7.无效-校园订单
8.无效-企业订单
9.无效-团购订单
10.无效-开增值税专用发票订单
11.无效-乡村推广员下单
12.无效-自己推广自己下单
13.无效-违规订单
14.无效-来源与备案网址不符
15.待付款
16.已付款
17.已完成
18.已结算（5.9号不再支持结算状态回写展示））注：自2018/7/13起，自己推广自己下单已经允许返佣，故12无效码仅针对历史数据有效
         */
        $status = [
            15 => "1",
            16 => "2",
            17 => "4",
            18 => "6",
        ];
        //拿到所有用
        /*
                $user_relation='';
                foreach($data as $k =>$v){
                    $user_id=$v['skuList'][0]['subUnionId'];
                    if($user_relation == ''){
                    $user_relation=$user_id;
                    }else{
                        if(!strstr($user_relation,$user_id)){
                        $user_relation .=','.$user_id;
                        }
                    }
                }
                $user= new User();
                $user_arr=$user->get_user_id_by_tb_rid($user_relation);
         */

        $order_model = new \Common\Models\Order();
        foreach ($data as $k => $v) {
            foreach ($v->detailList as $k1 => $v1) {
                $order_id     = $v->orderSn . '-' . $v1->goodsId;
                $order_status = $this->vph->get_status($v->orderSubStatusName);
                //	$v1['estimateFee']=rand(99,1000);
                $order_one = [
                    'user_id'            => $v->channelTag,
                    'order_id'           => $order_id,
                    'order_status'       => $order_status,
                    'goods_name'         => $v1->goodsName,
                    'goods_id'           => $v1->goodsId,
                    'goods_pic'          => $v1->goodsThumb,
                    'site'               => 'vph',
                    'price'              => $v1->commissionTotalCost,
                    'pay_money'          => $v1->commissionTotalCost,
                    'commition'          => $v1->commission,
                    'income_rate'        => $v1->commissionRate,
                    'order_create_time'  => date('Y-m-d H:i:s', $v->orderTime / 1000),
                    'order_paid_time'    => date('Y-m-d H:i:s', $v->orderTime / 1000),
                    'order_earning_time' => date('Y-m-d H:i:s', $v->signTime / 1000),
                    'settle_time'        => date('Y-m-d H:i:s', $v->settledTime / 1000),
                ];

                $order[$order_id]         = $order_one;
                $order_ids_arr[$order_id] = $order_status;

                if ($in_ids == '') {
                    $in_ids = "'$order_id'";
                } else {
                    $in_ids .= ",'$order_id'";

                }
            }
        }

        //订单去重
        $db_arr = $order_model->get_status_by_ids($in_ids, 'vph');

        $uporder = [];
        if ($db_arr) {
            foreach ($db_arr as $k => $v) {
                if ($order[$k]['order_status'] != $v) {
                    $uporder[$k] = $order[$k];
                }
                unset($order[$k]);
            }
        }

        //创建订单
        if ($order != []) {
            $order_model->create_update_order($order, 1);
        }
        //更新订单
        if ($uporder != []) {
            $order_model->create_update_order($uporder, 0);
        }

    }

    /**
     *  vph60天
     */
    public function vphLastMonthAction()
    {
        $now     = time();
        $control = new  \Common\Models\SyncControl();
        $res     = $control->find_by_site('vph_day');

        if (strtotime($res->end_time) > time()) {
            $res->end_time = date("Y-m-d H:i:s", strtotime("-60 day"));
        }

        $and           = 6;//小时
        $end_time      = (strtotime($res->end_time) + $and * 60 * 60) * 1000;
        $start_time    = strtotime($res->end_time) * 1000;
        $count         = 0;
        $res->end_time = date('Y-m-d H:i:s', $end_time / 1000);
        $res->save();
        //批量处理订单
        $data = $this->vph->get_order($start_time, $end_time);

        if ($data != []) {
            $count = count($data);
            $this->vph_order_deal($data);
        }
        $now = time() - $now;
        die(date('Y-m-d H:i:s', $start_time / 1000) . ' - ' . date('Y-m-d H:i:s', $end_time / 1000) . '用时:' . $now . '秒,获取' . $count . '条订单');
    }

    /**
     * vph每分钟
     */
    public function vphMinAction()
    {
        $now   = time();
        $start = (strtotime(date("Y-m-d H:i:00")) - 600) * 1000;
        $end   = (strtotime(date("Y-m-d H:i:59")) + 30) * 1000;

        $data  = $this->vph->get_order($start, $end);
        $count = 0;
        if ($data != []) {
            $count = count($data);
            $this->vph_order_deal($data);
        }
        $now = time() - $now;
        die(date("Y-m-d H:i:s", $start / 1000) . '-' . date("Y-m-d H:i:s", $end / 1000) . '用时:' . $now . '秒,获取' . $count . '条订单');
    }
    /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~end vph~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/


    /*----------------------------------------------beg suning------------------------------------------------------------*/

    public function suning_order_deal($data)
    {
        //拉取订单的集合
        //订单数组
        $order = [];
        //都好分割的数据
        $in_ids = '';
        //数据库返回的存在数据

        $status      = [
            '等待付款'  => 1,
            '支付完成'  => 2,
            '退款'    => 3,
            '订单已取消' => 11,
            '确认收货'  => 6,
        ];
        $user        = new User();
        $order_model = new Order();

        foreach ($data as $k => $v) {

            foreach ($v['orderDetail'] as $k1 => $v1) {
                $order_id     = $v1['orderLineNumber'];
                $order_status = $status[$v1['orderLineStatusDesc']];

                $where['conditions'] = "sn_pid = '{$v1['positionId']}'";
                $where['columns']    = "id";
                $userInfo            = $user->findFirst($where);
                if ($userInfo) {
                    $user_id = $userInfo->id;
                } else {
                    $user_id = -1;
                }
                $order_one = [
                    'user_id'           => $user_id,
                    'order_id'          => $order_id,
                    'order_status'      => $order_status,
                    'goods_name'        => $v1['productName'],
                    'goods_id'          => $v1['goodsNum'] . '-' . $v1['sellerCode'],
                    'goods_pic'         => $v1['pictureUrl'],
                    'site'              => 'suning',
                    'price'             => $v1['payAmount'],
                    'pay_money'         => $v1['payAmount'],
                    'commition'         => Common::number_randtwo($v1['payAmount'] * $v1['commissionRatio'], 3),
                    'income_rate'       => $v1['commissionRatio'],
                    'order_create_time' => $v1['orderSubmitTime'],
                    'order_paid_time'   => $v1['payTime'],
                ];

//                $orderInfo = $this->suning->get_order_info($v1['orderLineNumber']);

                if ($order_status == 6) {
                    $order_one['order_earning_time'] = $v1['orderLineStatusChangeTime'];
                    $order_one['settle_time']        = $v1['orderLineStatusChangeTime'];
                }
                if ($v1['violation'] == 1) {
                    $order_one['order_status'] = 5;
                    $order_one['order_chufa']  = 1;
                }
                if ($v1['promotion'] == 1) {
                    $order_one['order_status'] = 5;
                    $order_one['order_chufa']  = 1;
                }
                $order[$order_id]         = $order_one;
                $order_ids_arr[$order_id] = $order_status;

                if ($in_ids == '') {
                    $in_ids = "'$order_id'";
                } else {
                    $in_ids .= ",'$order_id'";

                }
            }
        }

        //订单去重
        $db_arr = $order_model->get_status_by_ids($in_ids, 'suning');

        $uporder = [];
        if ($db_arr) {
            foreach ($db_arr as $k => $v) {
                if ($order[$k]['order_status'] != $v) {
                    $uporder[$k] = $order[$k];
                }
                unset($order[$k]);
            }
        }

        //创建订单
        if ($order != []) {
            $order_model->create_update_order($order, 1);
        }
        //更新订单
        if ($uporder != []) {
            $order_model->create_update_order($uporder, 0);
        }

    }

    /**
     * 苏宁每分钟
     */
    public function suningMinAction()
    {
        $now = time();
        $params['start_time'] = date("Y-m-d H:i:00", $now - 120);
        $params['end_time']   = date("Y-m-d H:i:59", $now + 30);
        $data                 = $this->suning->get_order($params);
        $count                = 0;
        if ($data != []) {
            $count = count($data);
            $this->suning_order_deal($data);
        }
        $now = time() - $now;
        die($params['start_time'] . '-' . $params['end_time'] . '用时:' . $now . '秒,获取' . $count . '条订单');
    }

    /**
     * 苏宁以前的
     */
    public function suningLastMonthAction()
    {
        $now     = time();
        $control = new  \Common\Models\SyncControl();
        $key     = 'suning_day';
        $res     = $control->find_by_site($key);

        $days = strtotime("-60 day");
        if ($days >= strtotime($res->end_time) - 2 * 60 * 60) {

            $res->end_time   = date("Y-m-d H:i:s");
            $res->start_time = date("Y-m-d H:i:s", strtotime("-60 day"));
            $res->save();
        }

        $res = $control->find_by_site($key);

        $res->doing_time = time();
        $res->status     = 1;
        $res->save();
        $and        = 6;//小时
        $start_time = date('Y-m-d H:i:s', strtotime($res->end_time) - $and * 60 * 60);
        $end_time   = date('Y-m-d H:i:s', strtotime($res->end_time));
        $count      = 0;
        $res        = $control->find_by_site($key);
        if ($res->start_time > $res->end_time) {
            $res->end_time = '0000-00-00 00:00:00';
            $res->status   = 0;
            $res->save();
            die('执行完毕');
        }

        //批量处理订单
        $params['start_time'] = $start_time;
        $params['end_time']   = $end_time;
        $data                 = $this->suning->get_order($params);

        if ($data != []) {
            $count = count($data);
            $this->suning_order_deal($data);
        }
        $res->status     = 0;
        $res->doing_time = time();
        $res->end_time   = $start_time;
        $res->save();
        $now = time() - $now;
        die($start_time . ' - ' . $end_time . '用时:' . $now . '秒,获取' . $count . '条订单');
    }
    /*----------------------------------------------end suning-----------------------------------------------------------*/


    /***********************************************分佣************************************************************/

    /**
     * 计算补贴
     */
    public function calculateSubsidyAction()
    {
        $cache     = new \Common\BaseModel();
        $redis_key = "calculate_subsidy";
        $cache->set_cache($redis_key, time());
        $order      = new \Common\Models\Order();
        $order_list = $order->get_not_subsidy();
        if ($order_list->toArray() == []) {
            $cache->del_cache($redis_key);
            die('没有更多');
        }
        foreach ($order_list as $k => $v) {
            $msg = $order->calculate_commission($v);
            if ($msg !== true) {
                $v->user_id = 0;
                $v->remark  = $msg;
            }
            $v->is_calculation_money = 1;
            $v->save();
        }
        $cache->del_cache($redis_key);
        die('计算完成');
    }


}
